import JSONbig from 'json-bigint';
import { DataSet } from 'choerodon-ui/pro';
import { typeData, deployWayData } from './constants';

const mapping: any = {
  envId: {
    name: 'envId',
    type: 'string',
    label: '环境名称',
    textField: 'name',
    valueField: 'id',
  },
  checkEnvPermissionFlag: {
    name: 'skipCheckPermission',
    type: 'boolean',
    label: '是否允许非环境人员触发此部署任务',
    defaultValue: true,
  },
  deployType: {
    textField: 'name',
    valueField: 'value',
    defaultValue: deployWayData[0].value,
    name: 'deployType',
    type: 'string',
    label: '部署方式',
    options: new DataSet({
      data: deployWayData,
    }),
  },
  valueId: {
    name: 'valueId',
    type: 'string',
    label: '部署配置',
    textField: 'name',
    valueField: 'id',
  },
};

const getRequired = (level: any, type: any) => (level === 'project' && !window.location.href.includes('project-pipeline-template')) || type.includes('cd_');

const getDisabled = (level: any, type: any) => (level !== 'project' || window.location.href.includes('project-pipeline-template')) && !type.includes('cd_');

const Index = (
  projectId: any,
  useStore: any,
  appServiceId: any,
  level: any,
  type: any,
  BuildDataSet: any,
) => ({
  autoCreate: true,
  fields: Object.keys(mapping).map((key: any) => {
    const item = mapping[key];
    switch (key) {
      case 'envId': {
        item.disabled = (!appServiceId && !BuildDataSet?.current?.get('appServiceName')) || ((level !== 'project' || window.location.href.includes('project-pipeline-template')) && !type.includes('cd_'));
        item.required = getRequired(level, type);
        item.options = new DataSet({
          autoQuery: true,
          transport: {
            // @ts-ignore
            read: () => {
              if (projectId) {
                return ({
                  method: 'get',
                  //   url: `/devops/v1/projects/${projectId}/envs/
                  //   list_by_active?active=true&random=${random}`,
                  url: `/devops/v1/projects/${projectId}/envs/list_by_active?active=true`,
                  transformResponse: (res: any) => {
                    let newRes = res;
                    try {
                      newRes = JSONbig.parse(res);
                      useStore.setValueIdList(newRes.filter((r: any) => r.permission));
                      return newRes.filter((r: any) => r.permission);
                    } catch (e) {
                      return newRes;
                    }
                  },
                });
              }
              return undefined;
            },
          },
        });
        break;
      }
      case 'checkEnvPermissionFlag': {
        item.disabled = getDisabled(level, type);
        item.required = getRequired(level, type);
        break;
      }
      case 'deployType': {
        item.disabled = getDisabled(level, type);
        item.required = getRequired(level, type);
        break;
      }
      case 'valueId': {
        item.dynamicProps = {
          // required: ({ record }) => record?.get('type') === 'cdDeploy',
          disabled: ({ record }: any) => !record?.get('envId'),
          lookupAxiosConfig: ({ record }: any) => ({
            method: 'get',
            // 这里有删除一个random
            url:
                record?.get('envId')
                && `/devops/v1/projects/${projectId}/deploy_value/list_by_env_and_app?app_service_id=${appServiceId}&env_id=${record?.get('envId')}&createValueRandom=${useStore.getValueIdRandom}`,
            transformResponse: (res: any) => {
              let newRes = res;
              try {
                newRes = JSON.parse(res);
                newRes.push({
                  name: '创建部署配置',
                  id: 'create',
                });
                useStore.setValueIdList(newRes);
                return newRes;
              } catch (e) {
                newRes.push({
                  name: '创建部署配置',
                  id: 'create',
                });
                useStore.setValueIdList(newRes);
                return newRes;
              }
            },
          }),
        };
      }
    }
    return item;
  }),
});

export default Index;
